package com.watson.spring.all.security.service.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.watson.spring.all.security.service.old.entity.SecurityUser;
import com.watson.spring.all.security.service.old.entity.User;
import com.watson.spring.all.security.service.security.TokenManager;
import com.watson.spring.all.security.base.tool.Rdad;
import com.watson.spring.all.security.base.tool.ResponseUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

/**
 * @author watson
 * @date 2021/5/28 14:28
 * @Description: TODO
 **/
public class TokenLoginFilter extends UsernamePasswordAuthenticationFilter {
    private TokenManager tokenManager;
    private RedisTemplate redisTemplate;
    private AuthenticationManager authenticationManager;


    public TokenLoginFilter(AuthenticationManager authenticationManager, TokenManager tokenManager, RedisTemplate redisTemplate) {
        this.authenticationManager = authenticationManager;
        this.tokenManager = tokenManager;
        this.redisTemplate = redisTemplate;
        this.setPostOnly(false);
        this.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/admin/acl/login", "POST"));
    }

    //获取表单提交过来用户名和密码
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request,
                                                HttpServletResponse response) throws AuthenticationException {

        //获取表单提交过来的数据
        try {
            User user = new ObjectMapper().readValue(request.getInputStream(), User.class);
            return authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(
                            user.getUsername(),
                            user.getPassword(),
                            new ArrayList<>()));
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

    //认证成功调用的方法

    @Override
    protected void successfulAuthentication(HttpServletRequest request,
                                            HttpServletResponse response,
                                            FilterChain chain,
                                            Authentication authResult) throws IOException, ServletException {
        //认证成功之后，获取用户信息
        SecurityUser securityUser = (SecurityUser) authResult.getPrincipal();
        //根据用户生成token
        String token = tokenManager.createToken(securityUser.getCurrentUserInfo().getUsername());
        //将token刚入redis
        redisTemplate.opsForValue().set(securityUser.getCurrentUserInfo().getUsername(),
                securityUser.getPermissionValueList());
        //返回token
        ResponseUtil.out(response, Rdad.ok().data("token", token));


    }

    //认证失败调用的方法
    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request,
                                              HttpServletResponse response,
                                              AuthenticationException failed) throws IOException, ServletException {
        ResponseUtil.out(response, Rdad.error());
    }
}
